package com.mudalov.rec.dao.hibernate.util;

import com.mudalov.rec.dao.factory.DAOFactory;
import com.mudalov.rec.dao.interfaces.IAdminDAO;
import com.mudalov.rec.dao.interfaces.IRoleDAO;
import com.mudalov.rec.dao.interfaces.IStudentDAO;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.mudalov.rec.dao.model.study.Subject;
import com.mudalov.rec.dao.model.user.Admin;
import com.mudalov.rec.dao.model.user.Role;
import com.mudalov.rec.dao.model.user.Student;
import static com.mudalov.rec.dao.model.user.Role.*;

/**
 * Class <RecDbInitializer> represents tool for initialize REC database content
 * 
 * @author mudalov
 * 
 */
public class RecHbnDbInitializer extends HbnDbInitializer {
	
	public RecHbnDbInitializer(SessionFactory sessionFactory, Configuration configuration) {
		super(sessionFactory, configuration);
	}

	private final String[] INIT_SUBJECTS = { "Probability Theory",
			"Java SE", "Java EE" };
	
	private final String[] INIT_ROLES = {Type.ADMIN.toString(), Type.STUDENT.toString(), Type.TEACHER.toString()};

	public void initTableData() {
		initSubjects();
		initRoles();
        initUsers();
	}
	
	private void initSubjects() {
		Session session = getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();
		for (String subjectString : INIT_SUBJECTS) {
			Subject subjectObj = new Subject(subjectString);
			session.save(subjectObj);
		}
		tx.commit();
		session.close();
	}
	
	private void initRoles() {
		Session session = getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();
		for (String roleString : INIT_ROLES) {
			Role roleObj = new Role(roleString);
			session.save(roleObj);
		}
		tx.commit();
		session.close();
	}

    private void initUsers() {
        DAOFactory factory = DAOFactory.getFactory(DAOFactory.HIBERNATE_MY_SQL);
        IRoleDAO roleDAO = factory.getRoleDAO();
        Role studentRole = roleDAO.findObjectByProperty("name", Role.Type.STUDENT.toString());
        Role adminRole = roleDAO.findObjectByProperty("name", Role.Type.ADMIN.toString());

        Student testStudent = new Student("Test Student", "student", "student@mail.ru", null, "password", studentRole, "1234", null, null);
        IStudentDAO studentDAO = factory.getStudentDAO();
        studentDAO.save(testStudent);

        Admin admin = new Admin("Test Admin", "admin", "admin@google.com", null, "password", adminRole);
        IAdminDAO adminDAO = factory.getAdminDAO();
        adminDAO.save(admin);
    }
}
